<template>
  <div class="channel _page _container">
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs-info"
    />

    <InfoMain
      v-if="cardInfo"
      :key="`info-${cardInfo.title}`"
      :card="cardInfo"
      class="channel__info"
      type="channel"
    />

    <LazyUiExpandRow
      v-if="channelTags && channelTags.length > 0"
      :pre-text="`${$t('channel_tags')}:`"
      :items="channelTags"
      class="channel__tags"
      hydrate-on-idle
    />

    <SectionSwiperCards
      v-if="networkRoundCards.length > 0"
      :items="networkRoundCards"
      :title="$t('network_channels')"
      class="channel__network"
      placeholder-avatar="/img/logo-placeholder.svg"
    />

    <LazySectionToolbar
      class="channel__options"
      hydrate-on-idle
    />

    <GridVideos
      v-if="videosData && videosData.items && videosData.items.length > 0"
      :class="{'_loading': videosStatus === 'pending'}"
      :items="videosData.items"
      priority
    >
      <template #grid-end>
        <LazyAdvNativeBottom
          v-if="featureFlags.AdsNativeEnabled"
          hydrate-on-visible
        />
      </template>
      <template #default>
        <LazySectionSwiperCards
          v-if="modelsRoundCards.length > 0"
          :items="modelsRoundCards"
          :title="t('channels_popular_models')"
          class="channel__videos-models"
          placeholder-avatar="/img/model-placeholder.webp"
          hydrate-on-visible
        />
      </template>
    </GridVideos>
    <div
      v-else-if="videosStatus === 'pending'"
      class="channel__loading _loading"
    />
    <UiEmptyState v-else/>

    <LazyUiPagination
      v-if="videosData"
      arrow-icon
      :key="`pagination-${videosData.allPages}`"
      :total="videosData.allPages"
      class="channel__pagination _pagination"
      hydrate-on-visible
    />
  </div>
</template>

<script setup lang="ts">
import { convertString, convertQueryCategories, convertModelToRoundCard, convertChannelToRoundCard } from '../../runtime';
import { sortItemsDefault } from '../../lib';
import { ChannelsApiService } from '../../services/api/channels.service';
import { ModelsApiService } from '../../services/api/models.service';
import { VideosApiService } from '../../services/api/videos.service';
import type { IChipsItem, IPopularTags  } from '../../types';

const featureFlags = useRuntimeConfig().public.featureFlags;

const route = useRoute();
const { t } = useI18n();

const pageName = useGetPureRouteName();
const [
  { data: dataModels },
  { data: cardInfo, status },
  { data: videosData, status: videosStatus },
  { data: channelsTag },
] = await Promise.all([
  useFetchModelsByChannel(ModelsApiService.getListByChannel, 100),
  useFetchChannelsByName(ChannelsApiService.getChannelsByName),
  useFetchVideosByChannel(VideosApiService.getListByNicheAndChannel),
  useFetchPopularTagsByChannelName(VideosApiService.popularTagsByChannelName),
]);

const { data: networkChannels } = cardInfo.value?.isNetwork
    ? await useFetchChannelsByNetworkName(ChannelsApiService.getChannelsByNetworkName)
    : { data: ref(null) };

const title = convertString().fromSlug(String(route.params['channel']));
const metaTitle = computed(() => convertString().toCapitalize(title));

const routeQueryCategories = computed(() => {
  if (route.query['categories']) {
    const text = convertQueryCategories(route);
    return ` ${convertString().toCapitalize(text)}`;
  }
  return '';
});

const {
  meta
} = useMeta({
  t,
  pageKey: pageName,
  brandName: useAppConfig().brandName,
  sortOptions: sortItemsDefault,
  text: metaTitle,
  secondText: routeQueryCategories,
});

watchEffect(() => {
  useHead(meta.value);

  const isResolved = status.value === 'error' || status.value === 'success';
  if (isResolved && !cardInfo.value) {
    throw createError({ statusCode: 404, statusMessage: 'Not Found' });
  }
});

const breadcrumbs = [
  {
    name: `${t('navigation.main')}`,
    to: '/',
  },
  {
    name: `${t('navigation.channels')}`,
    to: '/channels',
  },
  {
    name: title,
  },
];

const networkRoundCards = computed(() =>
    networkChannels.value?.items?.map(convertChannelToRoundCard) || []
);

const modelsRoundCards = computed(() =>
    dataModels.value?.items?.map(convertModelToRoundCard) || []
);

const channelTags = computed<IChipsItem[]>(() => channelsTag.value?.map((item: IPopularTags) => ({
  title: item.title,
  value: item.title,
  prefix: 'tag'
})) || []);
</script>

<style lang="scss">
.channel__info {
  margin-bottom: 24px;
}

.channel__options {
  margin-bottom: 24px;
}

.channel__network {
  margin-bottom: 32px;
}

.channel__options:has(.ui-expand-row) {
  margin-bottom: 16px;
}

.channel__tags {
  margin-bottom: 24px;
}

.channel__navigation {
  display: flex;
  align-items: center;
  column-gap: 4px;
  padding-bottom: 8px;
  border-bottom: 1px solid $page-channel-border;

  @include from-br(sm) {
    padding-bottom: 16px;
    column-gap: 8px;
    justify-content: center;
  }
}

.channel__videos-models {
  grid-row: 2;
  grid-column: 1/-1;

  @include to-br(sm) {
    margin-block: 40px;
  }

  @include from-br(sm) {
    padding-block: 16px;
  }
}

.channel__footer-categories {
  padding-top: 48px;
  margin-top: auto;
}

.channel__pagination {
  margin-top: 32px;
}
</style>
